import React, { memo, useCallback, useMemo, useState } from 'react'

/**
 *  useCallback使用场景
 *  场景：在将一个组件中的函数，传递给子元素进行回调使用时，使用useCallback对函数进行处理
 */

const MXButton = memo((props) => {
  console.log(props.title,'MXButton Re render')
  return <button onClick={props.increment}>MXButton + 1</button>
})

export default function CallbackHookDemo02() {
  console.log('CallbackHookDemo02 Re render')

  const [count, setCount] = useState(0)
  const [show, setShow] = useState(true)

  const increment1 = () => {
    console.log('run increment1')
    setCount(count + 1)
  }

  const increment2 = useCallback(
    () => {
      console.log('run increment2')
      setCount(count + 1)
    }, [count]
  )

  const increment3 = useMemo(() => {
    return () => {
      console.log('run increment3')
      setCount(count + 1)
    }
  }, [count])

  return (
    <div>
      <h2>CallbackHookDemo01</h2>
      <h2>Currnet Count: {count}</h2>
      {/* <button onClick={increment1}>+1</button>
      <button onClick={increment2}>+1</button> */}
      <MXButton title="increment1" increment={increment1}/>
      <MXButton title="increment2" increment={increment2}/>

      <button onClick={e => setShow(!show)}>Show Switch</button>
    </div>
  )
}
